/*

 *
 */

package com.et114.components.rule.support;

import org.drools.WorkingMemory;

import com.et114.components.rule.RuleBaseLoader;
import com.et114.components.rule.RuleBaseManager;
import com.et114.components.rule.RuleTemplate;

import java.util.ArrayList;
import java.util.List;

public class RuleTemplateImpl implements RuleTemplate {
	private RuleBaseManager	ruleBaseManager	= new RuleBaseManager ( );
	
	public void setRuleBaseLoader ( RuleBaseLoader ruleBaseLoader ) {
		ruleBaseManager.setRuleBaseLoader ( ruleBaseLoader );
	}
	
	/**
	 * @see RuleTemplate#executeRules(List, String)
	 */
	public List executeRules ( List facts , String groupName ) throws Exception {
		WorkingMemory wm = ruleBaseManager.getSession ( groupName );
		for ( int i = 0 ; i < facts.size ( ) ; i ++ ) {
			Object obj = facts.get ( i );
			/*
			 * wm cannot assert null object, so it's necessary for validating
			 * the object before assertion
			 */
			if ( null == obj ) {
				continue;
			}
			wm.assertObject ( obj );
		}
		wm.fireAllRules ( );
		return wm.getObjects ( );
	}
	
	/**
	 * @see #executeRules(List)
	 */
	public List executeRules ( List facts ) throws Exception {
		return executeRules ( facts , null );
	}
	
	/**
	 * @see #executeRules(List, String)
	 */
	public List executeRules ( Object fact , String groupName )
			throws Exception {
		List facts = new ArrayList ( );
		facts.add ( fact );
		
		return executeRules ( facts , groupName );
	}
	
	/**
	 * @see #executeRules(Object)
	 */
	public List executeRules ( Object fact ) throws Exception {
		return executeRules ( fact , null );
	}
	
}
